package com.kpl.kplstzble.activity;

import static android.bluetooth.BluetoothGatt.GATT_SUCCESS;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;
import androidx.core.widget.ContentLoadingProgressBar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothProfile;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.kpl.kplstzble.R;
import com.kpl.kplstzble.adapter.BleDeviceAdapter;
import com.kpl.kplstzble.bean.BleDevice;
import com.kpl.kplstzble.utils.APKVersionCodeUtils;
import com.kpl.kplstzble.utils.BleConstant;
import com.kpl.kplstzble.utils.BleHelper;
import com.kpl.kplstzble.utils.ByteUtils;
import com.kpl.kplstzble.utils.DBUtils;
import com.kpl.kplstzble.utils.DataTrasportUtil;
import com.kpl.kplstzble.utils.DownloadUtil;


import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Objects;

import no.nordicsemi.android.support.v18.scanner.BluetoothLeScannerCompat;
import no.nordicsemi.android.support.v18.scanner.ScanCallback;
import no.nordicsemi.android.support.v18.scanner.ScanResult;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;

public class BlueToolthActivity extends AppCompatActivity {

    private String[] permissions = new String[]{Manifest.permission.ACCESS_FINE_LOCATION
            , Manifest.permission.ACCESS_COARSE_LOCATION
            , Manifest.permission.ACCESS_LOCATION_EXTRA_COMMANDS,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE};
    private static final int OPEN_SET_REQUEST_CODE = 100;
    private static final String TAG = com.kpl.kplstzble.MainActivity.class.getSimpleName();
    /**
     * 请求打开蓝牙
     */
    private static final int REQUEST_ENABLE_BLUETOOTH = 100;
    /**
     * 权限请求码
     */
    public static final int REQUEST_PERMISSION_CODE = 9527;

    /**
     * 蓝牙适配器
     */
    private BluetoothAdapter bluetoothAdapter;

    /**
     * nordic扫描回调
     */
    private ScanCallback scanCallback;
    /**
     * nordic扫描回调
     */
    private ScanCallback scanCallbacksetcode;
    /**
     * 设备列表
     */
    private List<BleDevice> mList = new ArrayList<>();

    /**
     * 需要设置编号设备列表
     */
    private List<BleDevice> setcodeList = new ArrayList<>();


    /**
     * 列表适配器
     */
    private BleDeviceAdapter deviceAdapter;

    /**
     * 加载进度条
     */
    private ContentLoadingProgressBar loadingProgressBar;

    /**
     * 等待连接
     */
    private LinearLayout layConnectingLoading;

    /**
     * Gatt`
     */
    private BluetoothGatt bluetoothGatt;

    /**
     * 设备是否连接
     */
    private boolean isConnected = false;

    /**
     * 设备是否连接
     */
    private boolean issettingcode = false;

    private Thread setcodethread;

    //待设置编号的设备序号
    private int setcodeorder = 0;

    //软件版本号
    private  String versionName;

    private Context context;

    private ProgressDialog progressDialogupload;
    private File file;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //检查更新软件
        context=this;
        versionName= APKVersionCodeUtils.getVerName(this);
        checkversion();
        try {
            PackageInfo pInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
            String version = pInfo.versionName;
            String label = getString(R.string.app_name_with_version, getString(R.string.app_name), version);
            setTitle(label);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }


        //检查Android版本
        checkAndroidVersion();
        if (lacksPermission(permissions)) {
            ActivityCompat.requestPermissions(this, permissions, OPEN_SET_REQUEST_CODE);
        } else {
            Log.i("LoginActivity", "");
        }
        //初始化
        initView();
        Context that = this;
        setcodethread = new Thread(() -> {
            while (true) {
                if (setcodeorder < setcodeList.size()) {
                    BluetoothDevice device = setcodeList.get(setcodeorder).getDevice();
                    System.out.println("待设置个数" + setcodeList.size());
                    System.out.println("正在设置：" + setcodeorder);
                    setcodeorder++;
                    //连接gatt 设置Gatt回调
                    bluetoothGatt = device.connectGatt(that, false, bluetoothGattCallback);
                    try {
                        Thread.sleep(3000);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    Calendar calendar = Calendar.getInstance();
                    String year = String.valueOf(calendar.get(Calendar.YEAR)).substring(2,4);

                    System.out.println("当前年份：" + year);
                    String month = String.valueOf(calendar.get(Calendar.MONTH) + 1); // 注意月份从0开始计数，所以要加1
                    System.out.println(month);

                    while (month.length()<2){
                        month="0"+month;
                    }
                    //boolean savedata = DBUtils.savedata(1);
                    String displaycode =String.valueOf(DBUtils.getdisplaycode()+1);
                    while (displaycode.length()<5){
                        displaycode="0"+displaycode;
                    }
                    String data = "XJXY140"+year+month+displaycode;
                    String hexdata = DataTrasportUtil.stringToHex(data);
                    hexdata = hexdata + "0000";

                    byte check = DataTrasportUtil.calculateChecksum(DataTrasportUtil.HexString2Bytes(hexdata));
                    String checkdata = DataTrasportUtil.byteToHex(check);
                    String senddata = "81" + checkdata + hexdata;
                    System.out.println("发送：" + senddata);
                    System.out.println("修改中。。。。。" + device.getName());

                    BleHelper.sendCommand(bluetoothGatt, senddata, "010200".equals(senddata));

                }
            }
        });
    }

    /**
     * 初始化
     */
    private void initView() {
        RecyclerView rvDevice = findViewById(R.id.rv_device);
        loadingProgressBar = findViewById(R.id.loading_progress_bar);
        layConnectingLoading = findViewById(R.id.lay_connecting_loading);
        Button startscan = (Button) findViewById(R.id.btn_start_scan);
        startscan.setOnClickListener(view -> {
            switch (view.getId()) {
                case R.id.btn_start_scan:
                    if (startscan.getText().equals(getString(R.string.start_scan))) {
                        startscan.setText(R.string.stop_scan);
                        startScanDevice();
                    } else if (startscan.getText().equals(getString(R.string.stop_scan))) {
                        startscan.setText(R.string.start_scan);
                        stopScanDevice();
                    }
                    break;
            }
        });
        /*Button btn_set = (Button) findViewById(R.id.btn_set);
        btn_set.setOnClickListener(view -> {
            switch (view.getId()) {
                case R.id.btn_set:
                    if (btn_set.getText().equals(getString(R.string.start_set))) {
                        btn_set.setText(R.string.stop_set);
                        startsetcode();
                    } else if (btn_set.getText().equals(getString(R.string.stop_set))) {
                        btn_set.setText(R.string.start_set);
                        stopsetcode();
                    }
                    break;
            }
        });*/
        //扫描结果回调
        scanCallback = new ScanCallback() {
            @Override
            public void onScanResult(int callbackType, @NonNull ScanResult result) {
                //if(result.getDevice().getName()!=null&&result.getDevice().getName().contains("AM")){
                //添加到设备列表
                if(result.getDevice().getName()!=null){
                    addDeviceList(new BleDevice(result.getDevice(), result.getRssi(), result.getDevice().getName()));
                }

                // }
            }

            @Override
            public void onScanFailed(int errorCode) {
                throw new RuntimeException("Scan error");
            }
        };
        //扫描结果回调
        scanCallbacksetcode = new ScanCallback() {
            @Override
            public void onScanResult(int callbackType, @NonNull ScanResult result) {
                if (result.getDevice().getName() != null && result.getDevice().getName().startsWith("AM")) {
                    //添加到设备列表
                    addDeviceListsetcode(new BleDevice(result.getDevice(), result.getRssi(), result.getDevice().getName()));
                }
            }

            @Override
            public void onScanFailed(int errorCode) {
                throw new RuntimeException("Scan error");
            }
        };
        //列表配置
        deviceAdapter = new BleDeviceAdapter(R.layout.item_device_rv, mList);
        rvDevice.setLayoutManager(new LinearLayoutManager(this));
        //item点击事件
        deviceAdapter.setOnItemClickListener((adapter, view, position) -> {
            //连接设备
            connectDevice(mList.get(position));
        });
        //启用动画
        deviceAdapter.setAnimationEnable(true);
        //设置动画方式
        deviceAdapter.setAnimationWithDefault(BaseQuickAdapter.AnimationType.SlideInRight);
        rvDevice.setAdapter(deviceAdapter);
    }

    /**
     * 连接设备
     *
     * @param bleDevice 蓝牙设备
     */
    private void connectDevice(BleDevice bleDevice) {
        //显示连接等待布局
        //layConnectingLoading.setVisibility(View.VISIBLE);
        //停止扫描
        stopScanDevice();

        //跳转页面
        Intent intent = new Intent(this, HomeActivity.class);
        intent.putExtra("device", bleDevice.getDevice());
        startActivity(intent);
    }

    /**
     * 添加到设备列表
     *
     * @param bleDevice 蓝牙设备
     */
    private void addDeviceList(BleDevice bleDevice) {
        if (!mList.contains(bleDevice)) {
            bleDevice.setRealName(bleDevice.getRealName() == null ? "UNKNOWN" : bleDevice.getRealName());
           // if (bleDevice.getRealName().startsWith("AM")) {
                mList.add(bleDevice);
          //  }
        } else {
            //更新设备信号强度值
            for (BleDevice device : mList) {
                device.setRssi(bleDevice.getRssi());
            }
        }
        //刷新列表适配器
        deviceAdapter.notifyDataSetChanged();
    }

    /**
     * 添加到设置编号设备列表
     *
     * @param bleDevice 蓝牙设备
     */
    private void addDeviceListsetcode(BleDevice bleDevice) {
        if (!setcodeList.contains(bleDevice)) {
            bleDevice.setRealName(bleDevice.getRealName() == null ? "UNKNOWN" : bleDevice.getRealName());
            if (bleDevice.getRealName().startsWith("AM")) {
                setcodeList.add(bleDevice);
                System.out.println("待设置个数+1");
            }
        } else {
            //更新设备信号强度值
            for (BleDevice device : setcodeList) {
                device.setRssi(bleDevice.getRssi());
            }
        }
        //刷新列表适配器
        deviceAdapter.notifyDataSetChanged();
    }

    /**
     * 开始扫描设备
     */
    public void startScanDevice() {
        loadingProgressBar.setVisibility(View.VISIBLE);
        mList.clear();
        deviceAdapter.notifyDataSetChanged();
        BluetoothLeScannerCompat scanner = BluetoothLeScannerCompat.getScanner();
        scanner.startScan(scanCallback);
    }

    /**
     * 停止扫描设备
     */
    public void stopScanDevice() {
        loadingProgressBar.setVisibility(View.INVISIBLE);
        BluetoothLeScannerCompat scanner = BluetoothLeScannerCompat.getScanner();
        scanner.stopScan(scanCallback);
    }

    /**
     * 开始设置显示器编号
     */
    public void startsetcode() {
        //是否在设置显示器编号状态
        issettingcode = true;
        //正在设置设备在集合中的下标重新置零
        setcodeorder = 0;
        //设置编号线程启动
        setcodethread.start();
        loadingProgressBar.setVisibility(View.VISIBLE);
        setcodeList.clear();
        deviceAdapter.notifyDataSetChanged();
        BluetoothLeScannerCompat scanner = BluetoothLeScannerCompat.getScanner();
        scanner.startScan(scanCallbacksetcode);
    }

    /**
     * 停止设置显示器编号
     */
    public void stopsetcode() {
        //不在设置显示器编号状态
        issettingcode = false;
        //终止设置编号线程
        setcodethread.stop();
        loadingProgressBar.setVisibility(View.INVISIBLE);
        BluetoothLeScannerCompat scanner = BluetoothLeScannerCompat.getScanner();
        scanner.stopScan(scanCallbacksetcode);
    }

    /**
     * 检查Android版本
     */
    private void checkAndroidVersion() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            //Android 6.0及以上动态请求权限
            requestPermission();
        } else {
            //检查蓝牙是否打开
            openBluetooth();
        }
    }


    //新版本检测
    private void checkversion() {
        new Thread(
                () -> {
                    String version = DBUtils.getbleversion();
                    Message msg= new Message();
                    if(version==null){
                        msg.what=2;
                    } else {
                        msg.obj=version;
                        msg.what=1;
                    }
                    uiHandler.sendMessage(msg);
                }

        ).start();

    }
    /**
     * 请求权限
     */
    @AfterPermissionGranted(REQUEST_PERMISSION_CODE)
    private void requestPermission() {
        String[] perms = {Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.ACCESS_COARSE_LOCATION,};
        if (EasyPermissions.hasPermissions(this, perms)) {
            //权限通过之后检查有没有打开蓝牙
            openBluetooth();
        } else {
            // 没有权限
            EasyPermissions.requestPermissions(this, "App需要定位权限", REQUEST_PERMISSION_CODE, perms);
        }
    }

    /**
     * 权限请求结果
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        // 将结果转发给 EasyPermissions
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    /**
     * 是否打开蓝牙
     */
    public void openBluetooth() {
        //获取蓝牙适配器
        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (bluetoothAdapter != null) {//是否支持蓝牙
            if (bluetoothAdapter.isEnabled()) {//打开
                showMsg("蓝牙已打开");
            } else {//未打开
                startActivityForResult(new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE), REQUEST_ENABLE_BLUETOOTH);
            }
        } else {
            showMsg("你的设备不支持蓝牙");
        }
    }

    /**
     * Toast提示
     * @param msg 内容
     */
    private void showMsg(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == REQUEST_ENABLE_BLUETOOTH) {
                if (bluetoothAdapter.isEnabled()) {
                    //蓝牙已打开
                    showMsg("蓝牙已打开");
                } else {
                    showMsg("请打开蓝牙");
                }
            }
        }
    }

    //判断是否获取权限
    public boolean lacksPermission(String[] permissions) {
        for (String permission : permissions) {
            //判断是否缺少权限，true=缺少权限
            if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
                return true;
            }
        }
        return false;
    }

    //蓝牙回调函数
    private final BluetoothGattCallback bluetoothGattCallback = new BluetoothGattCallback() {
        /**
         * 连接状态改变回调
         * @param gatt     gatt
         * @param status   gatt连接状态
         * @param newState 新状态
         */
        @Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
            Log.d(TAG, Thread.currentThread().getName());
            if (status == BluetoothGatt.GATT_SUCCESS) {
                switch (newState) {
                    case BluetoothProfile.STATE_CONNECTED://连接成功
                        Log.d(TAG, "连接成功");
                        //获取MtuSize
                        gatt.requestMtu(512);
                        break;
                    case BluetoothProfile.STATE_DISCONNECTED://断开连接
                        Log.e(TAG, "1断开连接");
                        break;
                    default:
                        break;
                }
            } else {
                Toast.makeText(getApplicationContext(), "蓝牙断开了", Toast.LENGTH_SHORT).show();
                Log.e(TAG, "onConnectionStateChange: " + status);
            }
        }

        /**
         * 物理层改变回调
         * @param gatt   gatt
         * @param txPhy  发送速率  1M 2M
         * @param rxPhy  接收速率  1M 2M
         * @param status 更新操作的状态
         */
        @Override
        public void onPhyUpdate(BluetoothGatt gatt, int txPhy, int rxPhy, int status) {
            Log.d(TAG, "onPhyUpdate: txPhy: " + txPhy + " rxPhy: " + rxPhy);
        }

        /**
         * 读取物理层回调
         * * @param gatt   gatt
         * @param txPhy  发送速率  1M 2M
         * @param rxPhy  接收速率  1M 2M
         * @param status 更新操作的状态
         */
        @Override
        public void onPhyRead(BluetoothGatt gatt, int txPhy, int rxPhy, int status) {
            Log.d(TAG, "onPhyRead: txPhy：" + txPhy + " rxPhy：" + rxPhy);
            if (txPhy == BluetoothDevice.PHY_LE_1M && rxPhy == BluetoothDevice.PHY_LE_1M) {
                //获取2M的发送和接收速率
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    gatt.setPreferredPhy(BluetoothDevice.PHY_LE_2M, BluetoothDevice.PHY_LE_2M,
                            BluetoothDevice.PHY_OPTION_NO_PREFERRED);
                }
            }
        }

        /**
         * 发现服务回调
         * @param gatt   gatt
         * @param status gatt状态
         */
        @Override
        public void onServicesDiscovered(BluetoothGatt gatt, int status) {
            Log.d(TAG, "onServicesDiscovered");
            boolean notifyOpen = BleHelper.enableIndicateNotification(gatt);

            if (!notifyOpen) {
                Log.e(TAG, "开启通知属性异常");
                gatt.disconnect();
            }
        }

        /**
         * 特性读取回调
         * @param gatt           gatt
         * @param characteristic 特性
         * @param status         gatt状态
         */
        @Override
        public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
            Log.d(TAG, "onCharacteristicRead: characteristic: " + characteristic.getUuid().toString());
        }

        /**
         * 特性写入回调
         * @param gatt           gatt
         * @param characteristic 特性
         * @param status         gatt状态
         */
        @Override
        public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
            String command = ByteUtils.bytesToHexString(characteristic.getValue());
            if (status == BluetoothGatt.GATT_SUCCESS) {
                Log.d(TAG, "onCharacteristicWrite: 写入成功：" + command);
            } else {
                Log.d(TAG, "onCharacteristicWrite: 写入失败：" + command);
            }
        }

        /**
         * 特性改变回调
         * @param gatt
         * @param characteristic 特性
         */
        @Override
        public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
            String hexString = ByteUtils.bytesToHexString(characteristic.getValue());
            System.out.println("收到数据11:" + hexString);
            if (Objects.requireNonNull(hexString).startsWith("41")) {
                int num = Integer.parseInt(DataTrasportUtil.hexToString(hexString.substring(4, 36)).substring(11, 16));
                boolean savedisplaycode = DBUtils.savedisplaycode(num);
                if(savedisplaycode){
                    System.out.println(num+"号改号成功");
                }else {
                    System.out.println(num+"已经存在或者改号失败");
                }
                gatt.disconnect();
            }
        }

        /**
         * 描述符获取回调
         * @param gatt       gatt
         * @param descriptor 描述符
         * @param status     gatt状态
         */
        @Override
        public void onDescriptorRead(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
            Log.d(TAG, "onDescriptorRead: descriptor: " + descriptor.getUuid().toString());
        }

        /**
         * 描述符写入回调
         * @param gatt       gatt
         * @param descriptor 描述符
         * @param status     gatt状态
         */
        @Override
        public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
            if (BleConstant.DESCRIPTOR_UUID.equalsIgnoreCase(descriptor.getUuid().toString())) {
                if (status == GATT_SUCCESS) {
                    Log.d(TAG, "onDescriptorWrite: 通知开启成功");
                    //获取phy
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                        gatt.readPhy();
                    }
                    //读取描述符
                    gatt.readDescriptor(descriptor);
                    //读取RSSI
                    gatt.readRemoteRssi();
                } else {
                    Log.d(TAG, "onDescriptorWrite: 通知开启失败");
                }
            }
        }

        /**
         * 可靠写入完成回调
         * @param gatt   gatt
         * @param status gatt状态
         */
        @Override
        public void onReliableWriteCompleted(BluetoothGatt gatt, int status) {
            Log.d(TAG, "onReliableWriteCompleted: 可靠写入");
        }

        /**
         * 读取远程设备的信号强度回调
         * @param gatt   gatt
         * @param rssi   信号强度
         * @param status gatt状态
         */
        @Override
        public void onReadRemoteRssi(BluetoothGatt gatt, int rssi, int status) {
            Log.d(TAG, "onReadRemoteRssi: rssi: " + rssi);
        }

        /**
         * Mtu改变回调
         * @param gatt   gatt
         * @param mtu    new MTU size
         * @param status gatt状态
         */
        @Override
        public void onMtuChanged(BluetoothGatt gatt, int mtu, int status) {
            Log.d(TAG, "onMtuChanged：mtu： " + mtu);
            //发现服务
            gatt.discoverServices();
        }
    };
    //升级弹窗
    private void showTip(Context context,String version) {
        AlertDialog dialog = new AlertDialog.Builder(context).setTitle("升级提示").setMessage("软件检测到新版本"+version+"，请升级")
                .setNeutralButton("取消", (dialog1, which) -> dialog1.dismiss()).setNegativeButton("升级", (dialog12, which) -> doDownload()).show();
        dialog.setCanceledOnTouchOutside(false);//可选
        dialog.setCancelable(false);//可选
    }
    //下载升级包
    private void doDownload() {
        String downloadUrl = "http://39.107.104.228:888/download/apk/kplstzble.apk"; //todo 实际下载地址应向平台查询

        String parentPath = "";
        try {
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
                parentPath = this.getExternalFilesDir(null).getPath();
            } else {
                parentPath = this.getFilesDir().getPath();
            }
        } catch (Exception e) {
            Log.d(TAG, "doDownload e:" + e.getMessage());
        }

        Log.d(TAG, "doDownload parentPath:" + parentPath);
        file = new File(parentPath, "cldz.apk");
        final String filePath = file.getAbsolutePath();

        //如果已有文件，删除
        if (file.exists()) {
            Log.d(TAG, "doDownload delete APK");
            file.delete();
        }
        progressDialogupload = new ProgressDialog(BlueToolthActivity.this);
        progressDialogupload.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialogupload.setTitle("正在下载");
        progressDialogupload.setMessage("请稍后...");
        progressDialogupload.setProgress(0);
        progressDialogupload.setMax(100);
        progressDialogupload.show();
        progressDialogupload.setCancelable(false);
        try {
            DownloadUtil.get().download(downloadUrl, filePath, new DownloadUtil.OnDownloadListener() {
                @Override
                public void onDownloadSuccess() {
                    //成功
                    if (progressDialogupload != null && progressDialogupload.isShowing()) {
                        progressDialogupload.dismiss();
                    }
                    Log.d(TAG, "doDownload download success");
                    installApk();
                }

                @Override
                public void onDownloading(int progress) {
                    progressDialogupload.setProgress(progress);
                    //进度
                    Log.d(TAG, "doDownload download:" + progress +"%");
                }

                @Override
                public void onDownloadFailed() {
                    //失败
                    Log.d(TAG, "doDownload download fail");
                }
            });
        } catch (Exception e) {
            Log.d(TAG, "doDownload e2:" + e.getMessage());
        }
    }

    //安装app
    private void installApk() {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        Uri data;
        String authority = getApplicationContext().getPackageName() + ".provider";
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        //7.0以上安卓系统安装app需要通过fileProvider（需要在AndroidManifest.xml声明）
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            data = FileProvider.getUriForFile(context, authority, file);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            Log.d(TAG,"installApk 7.0data:" + data);
        } else {
            data = Uri.fromFile(file);
            Log.d(TAG,"installApk data:" + data);
        }

        intent.setDataAndType(data, "application/vnd.android.package-archive");
        this.startActivity(intent);


    }
    private Handler uiHandler = new Handler() {
        public void handleMessage(Message msg) {
           if(msg.what == 1) {
                String version=(String) msg.obj;
                if(!versionName.contentEquals(version)) {
                    showTip(context,version);
                }
            }else if(msg.what == 2) {

            }
        }
    };
}